package com.spring.picture.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.spring.picture.config.CosClientConfig;
import com.spring.picture.exception.ErrorCode;
import com.spring.picture.exception.ThrowUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Component
public class CosManager {  
  
    @Resource
    private CosClientConfig cosClientConfig;
  
    @Resource  
    private COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 下载对象
     * @param key 唯一键
     * @return COSObject对象
     */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 上传图片，包括图片基本信息
     * @param key
     * @param file
     * @return
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        // 对图片进行处理 （获取图片基本信息也被认为是一种图片处理）
        PicOperations picOperations = new PicOperations();
        // 1表示返回原图信息
        picOperations.setIsPicInfo(1);
        List<PicOperations.Rule> rules = new ArrayList<>();
        // 图片压缩
        String webpKey = FileUtil.mainName(key) + ".webp";
        PicOperations.Rule rule = new PicOperations.Rule();
        rule.setBucket(cosClientConfig.getBucket());
        rule.setRule("imageMogr2/format/webp");
        rule.setFileId(webpKey);
        rules.add(rule);

        // 添加缩略图规则
        if (file.length() > 20*1024) {
            PicOperations.Rule thumbRule = new PicOperations.Rule();
            thumbRule.setBucket(cosClientConfig.getBucket());
            thumbRule.setFileId(FileUtil.mainName(key) + "_thumb." + FileUtil.getSuffix(key));
            thumbRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>",128,128));
            rules.add(thumbRule);
        }

        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 流式上传文件
     */
    public String uploadToCOS(MultipartFile multipartFile,  String key) throws Exception {
        ThrowUtils.throwIf(ObjectUtil.hasNull(multipartFile,key), ErrorCode.PARAMS_ERROR);

        InputStream inputStream = multipartFile.getInputStream();
        // 元信息配置
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(multipartFile.getSize());
        metadata.setContentType(multipartFile.getContentType());

        // 创建上传请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, inputStream, metadata);

        // 上传文件
        cosClient.putObject(putObjectRequest);

        // 生成访问链接
        return "https://" + cosClientConfig.getBucket() + ".cos." + cosClient.getClientConfig().getRegion().getRegionName()
                + ".myqcloud.com/" + key;

    }

    /**
     * 删除图片
     */
    public void deleteObject(String key) {
        cosClient.deleteObject(cosClientConfig.getBucket(), key);
    }

}
